﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Quartz;
using NLog;
using Quartz.Impl;
using Zhuang.WindowsService.Jobs;

namespace Zhuang.WindowsService
{
    public partial class Service1 : ServiceBase
    {

        private static Logger log;
        private ISchedulerFactory sf;
        private IScheduler sched;

        public Service1()
        {
            InitializeComponent();



            log = LogManager.GetCurrentClassLogger();

            sf = new StdSchedulerFactory();
            sched = sf.GetScheduler();

            log.Info("Initialized ImportService ctor");
        }

        protected override void OnStart(string[] args)
        {

            try
            {
                log.Info("Import Service is starting");

                #region  DefaultJob
                JobDetail DefaultJobDetail = new JobDetail("DefaultJobDetail", "ScheduleGroup", typeof(DefaultJob));
                sched.AddJob(DefaultJobDetail, true);

                CronTrigger DefaultJobCronTrigger = new CronTrigger("DefaultJobCronTrigger", "ScheduleGroup", "DefaultJobDetail", "ScheduleGroup", CronExpressionHelper.GetAppSettings("DefaultJobTime"), TimeZoneInfo.Local);
                DateTime DefaultJobDateTime = sched.ScheduleJob(DefaultJobCronTrigger);
                #endregion  DefaultJob

                IJobListener jobListener = new GlobalJobListener();
                sched.AddGlobalJobListener(jobListener);

                if (sched != null)
                {
                    sched.Start();

                    log.Info(DateTime.Now + " Import Service started");

                }
            }
            catch (Exception ex)
            {
                log.Info(ex.Message.ToString());
            }
        }

        protected override void OnStop()
        {
            log.Info("Import Service is stopping");

            try
            {
                if (sched.IsStarted)
                {
                    sched.Shutdown(false);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                log.Error(ex.StackTrace, ex);
            }

            log.Info("Import Service stopped");
        }
    }
}
